<template>
  <div>
    <el-main>
      <el-row>
        <el-button @click='dialogVisible = true' v-if="rid == 0" type="primary">上传行业报告</el-button>
      </el-row>
      <el-table style="width:90%" :header-cell-style="{background:'#F3F8FE'}" align="center" :data="tableData" border
        class="tableHeight">
        <el-table-column align="center" label="封面图">
          <template slot-scope="scope">
            <div style="position: relative;width:100%;padding-top:56%;">
              <img style="width:100%;
                                      height:100%;
                                      position: absolute;
                                      left: 0;
                                      top:0;
                                      "
                :src="scope.row.thumb" alt="">
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" prop="industry_name" label="名称">
        </el-table-column>
        <el-table-column align="center" prop="industry_name" label="行业">
        </el-table-column>
        <el-table-column align="center" label="文件">
          <template slot-scope="scope">
            <a @click="openUrl(scope.row.file)" style="color: #3377FF;">{{scope.row.fname}}</a>
            <a @click="DownLoad(scope.row)" style="color: #3377FF;"> <i style="padding-left:20px;" class="el-icon-download">下载</i></a>
          </template>
        </el-table-column>
        <el-table-column v-if="rid == 0" align="center" label="操作">
          <template slot-scope="scope">
            <el-button class="editText" @click="etitItem(scope.row.id)" type="text">编辑</el-button>
            <el-button class="deletText" @click="deleteItem(scope.row.id)" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination" style="width:90%">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page.page"
          :page-size="page.page_size" layout="total, prev, pager, next, jumper" :total="page.count" align='left'></el-pagination>
      </div>
    </el-main>
    <el-dialog :close-on-click-modal='false' title="行业报告" :visible.sync="dialogVisible" width="40%" :before-close="handleClose">
      <el-form ref="form" :label-position="labelPosition" :model="form" label-width="100px">
        <el-form-item prop="thumb" label="封面图">
          <!-- :data="{id:item.id}" -->
          <div class="license_box">
            <el-upload ref="upload" accept="image/*" :headers="{Authorization :token}" :on-success="onSuccess"
              :on-error="onError" :show-file-list="false" :action="`${VUE_APP_BASE_API}/v1/index/upload`">
              <img v-if="form.thumb" :src="form.thumb" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

          </div>
          <span slot="footer" class="dialog-footer">
            <el-row type="flex" :gutter="20">
              <el-col :lg="24">
                <div style="display: flex;justify-content: center;">
                  <el-upload ref="upload" :headers="{Authorization :token}" :on-success="onSuccess" :on-error="onError"
                    :show-file-list="false" :action="`${VUE_APP_BASE_API}/v1/index/upload`">
                  </el-upload>
                </div>
              </el-col>
            </el-row>
          </span>
        </el-form-item>
        <el-form-item prop="name" label="名称">
          <el-input placeholder="请输入名称" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item prop="industry_id" label="行业">
          <el-select style="width:100%;" v-model="form.industry_id" placeholder="请选择行业">
            <el-option v-for="item in cate" :key="item.id" :label="item.iname" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="file" label="文件">
          <!-- <el-input ></el-input> -->
          <el-upload class="upload-demo" :action="`${VUE_APP_BASE_API}/v1/index/upload`" :on-success="onSuccessFile"
            :on-error="onError" :limit="1" :show-file-list="false">
            <!-- :file-list="fileList" -->
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
          <span v-if="form.fname">{{form.fname}}</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="button" class="pubBtn2" @click="cancle('form')">取消</el-button>
        <el-button type="button" class="pubBtn" @click="Save('form')">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    mapGetters
  } from 'vuex'
  import {
    getToken
  } from '@/utils/auth'
  import {
    VUE_APP_BASE_API
  } from "@/config.js"
  import {
    IndustryIndex,
    IndustryCate,
    IndustryCreate,
    IndustryDelete,
    IndustryUpdate,
    IndustryInfo,
    IndustryDownLoad
  } from "@/api/admin"

  export default {
    data() {
      return {
        VUE_APP_BASE_API,
        uploadData: {},
        token:getToken(), //getToken(),
        tableData: [],
        labelPosition: "top",
        form: {
          name: '',
          industry_id: '',
          thumb: '',
          file: '',
          id: '',
          fname: ''
        },
        dialogVisible: false,
        cate: [],
        page: [],
      }
    },
    computed: {
      ...mapGetters([
        'sidebar',
        'avatar',
        'name',
        'roles',
        'type',
        'rid'
      ]),
    },
    mounted() {
      this.getList()
    },
    methods: {
      async getList() {
        try {
          const res = await IndustryIndex()
          this.tableData = res.list
          this.page = res.page
          this.cate = await IndustryCate()
        } catch (e) {
          this.$message.error(e.message)
        }
      },
      cancle(formName) {
        this.dialogVisible = false
        this.form.id = '';
        this.form.fname = ''
        this.$refs[formName].resetFields();
      },
      async Save(formName) {
        if (!this.form.id) {
          try {
            const {
              name,
              industry_id,
              thumb,
              file,
              fname
            } = this.form;
            const res = await IndustryCreate({
              name,
              industry_id,
              thumb,
              file,
              fname
            })
            this.getList()
            this.dialogVisible = false
            this.form.fname = ''
            this.$refs[formName].resetFields();
            this.$message.success("保存成功")
          } catch (e) {
            this.$message.error(e.message)
          }
        } else {
          try {
            const {
              name,
              industry_id,
              thumb,
              file,
              id,
              fname
            } = this.form;
            const res = await IndustryUpdate({
              id,
              name,
              industry_id,
              thumb,
              file,
              fname
            })
            this.getList()
            this.dialogVisible = false
            this.form.fname = ''
            this.$refs[formName].resetFields();
            this.form.id = ''
            this.$message.success("修改成功")
          } catch (e) {
            this.$message.error(e.message)
          }

        }
      },
      async etitItem(id) {
        try {
          this.dialogVisible = true;
          this.form.id = id
          const res = await IndustryInfo({
            id: id
          })
          this.form = res;
          // this.fileList.push(res.fname)
        } catch (e) {
          this.$message.error(e.message)
        }
      },
      async deleteItem(id) {
        this.$confirm('是否删除行业报告', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await IndustryDelete({
              id: id
            })
            this.getList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } catch (e) {
            this.$message.error(e.message)
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleClose() {
        this.dialogVisible = false;
        this.form.id = ''
        this.form.fname = ''
        this.$refs[formName].resetFields();
      },
      async onSuccess(response, file, fileList) {
        if (response) {
          this.form.thumb = response.data.url
          this.$nextTick(() => {
            this.form.thumb = response.data.url
            this.$emit("cancle", false)
          })
          this.$message.success("上传成功");
          this.$emit("cancle", false)
        }
      },
      async onSuccessFile(response, file, fileList) {

        if (response) {
          this.form.fname = file.name
          this.form.file = response.data.url
          this.$nextTick(() => {
            this.form.file = response.data.url
            this.$emit("cancle", false)
          })
          this.$message.success("上传成功");
          this.$emit("cancle", false)
        }
      },

      onError(err) {
        if (err) {
          this.$message.error("上传失败");
        }
      },
      //每页下拉显示数据
      async handleSizeChange(size) {
        try {
          const res = await IndustryIndex({
            page: size,
          })
          this.tableData = res.list
          this.page = res.page
        } catch (e) {
          this.$message.error(e.message);
        }
      },
      //点击第几页
      async handleCurrentChange(currentPage) {
        try {
          const res = await IndustryIndex({
            page: currentPage,
          })
          this.tableData = res.list
          this.page = res.page
        } catch (e) {
          this.$message.error(e.message);
        }
      },
      async openUrl(file) {
        window.open(file)
        // try{
        //   const res = await IndustryDownLoad({id:id})
        //   window.open(file)
        // } catch (e){
        //  this.$message.error(e.message);
        // }
      },
      async DownLoad(item) {
        const res = await IndustryDownLoad({
          id: item.id
        })
        const blob = new Blob([res.data]);
        const fileName = item.fname;
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      }
    }
  }
</script>

<style scoped lang="less">
  .license_box {
    width: 100%;
    height: 200px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(230, 233, 240, 1);
    border-radius: 5px;
    margin: 0 auto;
    position: relative;
    text-align: center;

    .avatar {
      display: block;
      width: 100%;
      height: 200px;
      object-fit: contain;
    }
  }

  .avatar-uploader-icon {
    font-size: 50px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
</style>
